package com.owen.liferay.jdo.domain;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.jdo.Query;
import javax.jdo.Transaction;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

@PersistenceCapable(detachable="true", table="users_teams")
public class TeamUsers {
	
	final private static String TNAME = "users_teams";
	
	final static PersistenceManagerFactory PMF = JDOHelper.getPersistenceManagerFactory("datanucleus.properties");

	@Persistent
	private long userId;
	
	@Persistent
	private long teamId;
	
	public static List<Long> findTeams(long userId) {
		
		System.out.println("findTeamUsers is: " + userId);

		PersistenceManager pm = PMF.getPersistenceManager();

		Transaction tx = pm.currentTransaction();

		List<TeamUsers> teamUsers = null;
		
		List<Long> teamIds = new ArrayList<Long>();

		try {
			tx.begin();

			Query q = pm.newQuery(TeamUsers.class, "userId == :userId");

			teamUsers = (List<TeamUsers>) q.execute(userId);

			Iterator<TeamUsers> iter = teamUsers.iterator(); 
			
			System.out.println("query completed, teamUsers returned are: " + teamUsers.size());
			
			while (iter.hasNext()) {
				TeamUsers teamu = pm.detachCopy(iter.next());
				teamIds.add(teamu.getTeamId());
			}

			tx.commit();
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			pm.close();
		}

		return teamIds;
	}

	public long getUserId() {
		return userId;
	}

	public void setUserId(long userId) {
		this.userId = userId;
	}

	public long getTeamId() {
		return teamId;
	}

	public void setTeamId(long teamId) {
		this.teamId = teamId;
	}

	

}
